export default {
  name: "plugin-treeData",
  /**
   * parentId
   * children
   * @param items
   * @param rootId 根节点
   * @return {*[]}
   */
  arrayToTree: (items,key='id',parentId='parentId', rootId = 0) => {
    let nodesMap = {};
    let treeData = [];

    // 创建节点映射
    items.forEach(item => {
      nodesMap[item[key]] = {...item, children: []};
    });

    // 构建树形结构
    items.forEach(item => {
      if (item[parentId] === rootId) {
        treeData.push(nodesMap[item[key]]);
      } else {
        nodesMap[item[parentId]]?.children.push(nodesMap[item[key]]);
      }
    });
    Object.keys(nodesMap).forEach(x=>{
      if(nodesMap[x].children?.length == 0){
        nodesMap[x].children = null
      }
    })
    return treeData;
  }
};
